/*
给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。


示例 1：
1-2-3-4-5
   ↓
5-4-3-2-1

输入：head = [1,2,3,4,5]
输出：[5,4,3,2,1]

*/

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

/**
 * @param {number[]} head
 * @return {ListNode}
 */
const init = (arr) => {
    let first = null, p = null
    for (const item of arr) {
        const node = new ListNode(item)
        if (!first) {
            first = node
            p = first
            continue
        }
        p.next = node
        p = node
    }
    return first
}

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {number[]} head
 * @return {ListNode}
 */
var reverseList = function (head) {
    const node = init(head)

    let first, p, last
    do {
        if (!p) {
            p = node
            first = p
            last = p
            continue
        }
        if (last == null) break
        const newNode = last
        last = newNode.next

        p = first
        first = newNode
        first.next = p

        //转到下一项
    } while (p.next != null)
    return first
};

console.log(reverseList([1, 2, 3, 4, 5, 6, 7]))